import axios from "axios";
import {useTokenStore} from "@/stores/token.js";
import router from "@/router/index.js";
import {ElMessage} from "element-plus";
import {useUserStore} from "@/stores/user.js";
//创建axios对象
const service=axios.create({
    baseURL:import.meta.env.VITE_SERVER_ADDR
});

// 添加请求拦截器
service.interceptors.request.use(req => {
    const tokenStore = useTokenStore();
    // 在发送请求之前做些什么
    if(tokenStore.tokenStr){
        req.headers.token = tokenStore.tokenStr;
    }
    return req;
}, error => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

//响应拦截器
service.interceptors.response.use(resp=>{
    //刷新token
    const token = resp.headers.token;
    if(token){
        const tokenStore = useTokenStore();
        tokenStore.updateToken(token);
    }
    return resp.data;
},error => {
    // 对响应错误做点什么
    if (error.status == 403) {
        ElMessage.error({
            message: "令牌错误请重新登录",
            duration: 1000,
            onClose: () => {
                const tokenStore = useTokenStore();
                const userStore = useUserStore();
                userStore.$reset();
                tokenStore.$reset();
                //跳转到首页
                let currentPath = router.currentRoute.value.path;
                if(currentPath.startsWith("/admin")){
                    router.push( "/admin/login");
                }else {
                    router.push( "/user/login");
                }
            }
        });
    }
});

export default service;